<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-row>
            <!-- 店铺名称 -->
            <el-form-item prop="name">
              <el-input
                :placeholder="$t('店铺名称')"
                v-model="queryParams.name"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 店铺电话 -->
            <el-form-item prop="tel">
              <el-input
                :placeholder="$t('店铺电话')"
                v-model="queryParams.tel"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 店铺邮编 -->
            <el-form-item prop="postcode">
              <el-input
                :placeholder="$t('店铺邮编')"
                v-model="queryParams.postcode"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 店铺地址 -->
            <el-form-item prop="address">
              <el-input
                :placeholder="$t('店铺地址')"
                v-model="queryParams.address"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- 店铺负责人 -->
            <el-form-item prop="shopAdmin">
              <el-input
                :placeholder="$t('店铺负责人')"
                v-model="queryParams.shopAdmin"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="distrName" v-if="isPlatform()">
              <el-input
                :placeholder="$t('卖家名称')"
                v-model="queryParams.distrName"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>

            <el-form-item prop="platformType" v-if="isPlatform()">
              <el-select
                style="width: 100%"
                :placeholder="$t('请选择')"
                clearable
                @keyup.enter.native="handleQuery"
                v-model="queryParams.platformType"
              >
                <el-option
                  v-for="item in shop_type_list"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['distribution:distributorShop:add']"
        >
          <!-- 新增 -->
          {{ $t('添加') }}
        </el-button>
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['distribution:distributorShop:edit']"
        >
          {{ $t('编辑') }}
        </el-button> -->
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['distribution:distributorShop:remove']"
        >
          <!-- 删除 -->
          {{ $t('删除') }}
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['distribution:distributorShop:export']"
        >
          <!-- 导出 -->
          {{ $t('导出') }}
        </el-button>
      </template>
    </PageSearch>

    <el-table
      :height="calTableHeight()"
      v-loading="loading"
      ref="TableRef"
      :data="distributorShopList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
      <!-- 店铺名称 -->
      <el-table-column :label="$t('店铺名称')" align="center" prop="name" />
      <!-- 账户类型 -->
      <el-table-column :label="$t('账户类型')" align="center" prop="platformType">
        <template slot-scope="scope">
          {{ handleShopType(scope.row.platformType) }}
        </template>
      </el-table-column>
      <!-- logo -->
      <el-table-column label="logo" align="center" prop="logo">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :key="Math.random()"
            v-hover="scope.row.corporationLogo"
            :src="scope.row.corporationLogo + '?x-oss-process=image/resize,w_100/quality,q_70'"
          />
        </template>
      </el-table-column>
      <!-- 公司印章 -->
      <el-table-column :label="$t('公司印章')" align="center" prop="corporationSignet">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            :key="Math.random()"
            v-hover="scope.row.corporationSignet"
            :src="scope.row.corporationSignet + '?x-oss-process=image/resize,w_100/quality,q_70'"
          />
        </template>
      </el-table-column>

      <el-table-column :label="$t('公司税号')" align="center" prop="corporationTax" />

      <!-- 店铺电话 -->
      <el-table-column :label="$t('店铺电话')" align="center" prop="tel" />
      <!-- 店铺邮编 -->
      <el-table-column :label="$t('店铺邮编')" align="center" prop="postcode" />
      <!-- 店铺地址 -->
      <el-table-column :label="$t('店铺地址')" align="center" prop="address" show-overflow-tooltip width="200" />
      <!-- 店铺负责人 -->
      <el-table-column :label="$t('店铺负责人')" align="center" prop="shopAdmin" />

      <!-- 卖家名称 -->
      <el-table-column :label="$t('卖家名称')" align="center" prop="distrName" />
      <!-- 验证码 -->
      <el-table-column :label="$t('验证码')" align="center" prop="checkCode" />
      <!-- 是否启用验证码 -->
      <el-table-column show-overflow-tooltip align="center" :label="$t('是否启用验证码')" prop="isUse">
        <template slot-scope="{ row }">
          <!-- status 0:正常 1:停用 -->
          <el-switch
            :disabled="!canEditCheckCode"
            v-model="row.isUse"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <!-- 备注 -->
      <el-table-column :label="$t('备注')" align="center" prop="remark" />
      <!-- 操作 -->
      <el-table-column :label="$t('操作')" align="center" :width="calWidth(150, 200, 150)">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['distribution:distributorShop:edit']"
          >
            <!-- 修改 -->
            {{ $t('编辑') }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['distribution:distributorShop:remove']"
          >
            <!-- 删除 -->
            <span style="color: red">
              {{ $t('删除') }}
            </span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商家店铺关联对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 店铺名称 -->
        <el-form-item :label="$t('店铺名称')" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <!-- 店铺电话 -->
        <el-form-item :label="$t('店铺电话')" prop="tel">
          <el-input v-model="form.tel" />
        </el-form-item>
        <!-- 店铺邮编 -->
        <el-form-item :label="$t('店铺邮编')" prop="postcode">
          <el-input v-model="form.postcode" />
        </el-form-item>
        <!-- 店铺地址 -->
        <el-form-item :label="$t('店铺地址')" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <!-- 店铺负责人 -->
        <el-form-item :label="$t('店铺负责人')" prop="shopAdmin">
          <el-input v-model="form.shopAdmin" />
        </el-form-item>
        <!-- 店铺类型 -->
        <el-form-item label="店铺类型" prop="platformType">
          <el-select style="width: 100%" v-model="form.platformType">
            <el-option
              v-for="item in shop_type_list"
              :label="item.dictLabel"
              :value="item.dictValue"
              :key="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <!-- 按卖家快递要求 -->
        <el-form-item label-width="140px" :label="$t('按买家快递要求')" prop="userExpressRequire">
          <el-radio v-model="form.userExpressRequire" :label="2">要求</el-radio>
          <el-radio v-model="form.userExpressRequire" :label="1">不要求</el-radio>
        </el-form-item>
        <!-- 商家ID -->
        <el-form-item :label="$t('商家ID')" prop="distrId">
          <el-input disabled v-model="form.distrId" />
        </el-form-item>
        <!-- 备注 -->
        <el-form-item :label="$t('备注')">
          <el-input v-model="form.remark" type="textarea" />
        </el-form-item>
        <!-- 官网地址 -->
        <el-form-item :label="$t('官网地址')">
          <el-input v-model="form.link" />
        </el-form-item>

        <el-form-item :label="$t('公司税号')">
          <el-input v-model="form.corporationTax" />
        </el-form-item>

        <!-- 官网地址 -->
        <el-form-item :label="$t('面单打印1')" style="position: relative">
          <div style="position: absolute; left: -20px; top: -27px">
            <el-popover placement="top-start" width="700" trigger="click">
              <div>
                <el-image :preview-src-list="[templateImg]" style="width: 650px" :src="templateImg" alt="" />
              </div>
              <el-button type="text" icon="el-icon-warning" slot="reference"></el-button>
            </el-popover>
          </div>
          <el-input v-model="form.print1" />
        </el-form-item>
        <!-- 面单打印 -->
        <el-form-item :label="$t('面单打印2')">
          <el-input v-model="form.print2" />
        </el-form-item>
        <!-- 面单打印 -->
        <el-form-item :label="$t('面单打印3')">
          <el-input v-model="form.print3" />
        </el-form-item>
        <!-- 面单打印 -->
        <el-form-item :label="$t('面单打印4')">
          <el-input v-model="form.print4" />
        </el-form-item>
        <!-- 面单打印 -->
        <el-form-item :label="$t('面单打印5')">
          <el-input v-model="form.print5" />
        </el-form-item>
        <!-- 面单打印 -->
        <el-form-item :label="$t('面单打印6')">
          <el-input v-model="form.print6" />
        </el-form-item>
        <el-form-item :label="$t('致谢词')">
          <el-input v-model="form.acknowledgment" />
        </el-form-item>

        <!-- logo -->
        <el-form-item label="logo" prop="corporationLogo">
          <ImgUploadManage :needSplit="false" :businessId="form.id" type="5" :fileList.sync="form.corporationLogo" />
          <span style="color: red">{{ $t('建议上传比例为16:9的图片') }}</span>
        </el-form-item>
        <!-- 公司印章 -->
        <el-form-item :label="$t('公司印章')" prop="corporationSignet">
          <ImgUploadManage :needSplit="false" :businessId="form.id" type="5" :fileList.sync="form.corporationSignet" />
          <span style="color: red">{{ $t('建议上传比例为3:4的图片') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">
          <!-- 确 定 -->
          {{ $t('确定') }}
        </el-button>
        <el-button @click="cancel">
          <!-- 取 消 -->
          {{ $t('取消') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDistributorShop,
  delDistributorShop,
  forbidden,
  getDistributorShop,
  listDistributorShop,
  updateDistributorShop,
} from '@/api/distribution/sku/distributorShop'
import templateImg from '@/assets/images/print-template.png'

import { checkPermi } from '@/utils/permission'
import { useDict } from '@/utils/useDict'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'DistributorShop',
  data() {
    return {
      templateImg,
      /**店铺类型列表 */
      shop_type_list: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 商家店铺关联表格数据
      distributorShopList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        tel: undefined,
        postcode: undefined,
        address: undefined,
        shopAdmin: undefined,
        platformType: undefined,
        distrId: undefined,
        distrName: undefined,
      },
      // 表单参数
      form: {
        userExpressRequire: 2,
        //
        corporationLogo: '',
        //
        corporationSignet: '',
      },
      // 表单校验
      rules: {
        id: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        name: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        tel: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        postcode: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        address: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        shopAdmin: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        platformType: [
          {
            required: true,
            message: this.$t('请选择'),
            trigger: 'blur',
          },
        ],
        platformType: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'change',
          },
        ],
        distrId: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
        remark: [
          {
            required: true,
            message: this.$t('请输入'),
            trigger: 'blur',
          },
        ],
      },
    }
  },
  computed: {
    canEditCheckCode() {
      return checkPermi(['distribution:distributorShop:forbidden'])
    },
  },
  created() {
    this.getList()
    useDict('shop_type').then(({ shop_type }) => {
      this.shop_type_list = shop_type.map((item) => {
        return {
          ...item,
          dictValue: +item.dictValue,
        }
      })
    })
  },
  methods: {
    isPlatform() {
      const distr = JSON.parse(localStorage.getItem('distr') || '{}')
      return !distr.distrId
    },
    // 是否启用验证码
    //  status  0:正常 1:停用
    handleStatusChange(row) {
      const data = {
        id: row.id,
        isUse: row.isUse,
      }
      console.log(`data ==>`, JSON.parse(JSON.stringify(data)))
      forbidden(data)
        .then((res) => {
          const { code, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })

            this.getList()
          }
        })
        .catch(() => {
          row.isUse == 0 ? (row.isUse = 1) : (row.isUse = 0)
        })
    },
    handleShopType(type) {
      const shop_type = this.shop_type_list.filter((i) => i.dictValue == type)
      return shop_type[0]?.dictLabel
    },
    setImg(res, key) {
      this.form[key] = res.url
    },
    handleRemove(key) {
      this.form[key] = ''
      // console.log(` this.form ==>`, JSON.parse(JSON.stringify(this.form)))
    },
    /** 查询商家店铺关联列表 */
    getList() {
      this.loading = true
      listDistributorShop(this.queryParams).then((response) => {
        this.distributorShopList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        tel: undefined,
        postcode: undefined,
        address: undefined,
        shopAdmin: undefined,
        platformType: undefined,
        userExpressRequire: 2,
        distrId: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        corporationLogo: '',
        corporationSignet: '',
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.pageSize = 10
      this.queryParams.pageNum = 1
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.distrId = JSON.parse(localStorage.getItem('distr') || '{}').distrId || ''
      this.open = true
      this.title = this.$t('添加')
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const id = row.id || this.ids
      getDistributorShop(id).then((response) => {
        this.loading = false
        this.form = { ...response.data }
        this.open = true
        this.title = this.$t('编辑')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateDistributorShop(this.form)
              .then((res) => {
                const { code, data, msg } = res
                if (code === 200) {
                  this.$message({ type: 'success', message: msg })

                  this.open = false
                  this.getList()
                }
              })
              .finally(() => {
                this.buttonLoading = false
              })
          } else {
            addDistributorShop(this.form)
              .then((res) => {
                const { code, data, msg } = res
                if (code === 200) {
                  this.$message({ type: 'success', message: msg })

                  this.open = false
                  this.getList()
                }
              })
              .finally(() => {
                this.buttonLoading = false
              })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm(this.$t('确定删除?'))

        .then(() => {
          this.loading = true
          return delDistributorShop(ids)
        })
        .then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })

            this.loading = false
            this.getList()
          }
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'distribution/distributorShop/export',
        {
          ...this.queryParams,
        },
        `distributorShop_${new Date().getTime()}.xlsx`,
      )
    },
  },
}
</script>

<style scoped>
.bigImg {
  border-radius: 3px;
  z-index: 10;
  position: fixed;
  width: 200px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
